import com.mysql.cj.jdbc.Driver;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @Author Luming
 * @Date 2024/5/15 13:56
 * @Description:
 */
@WebServlet("/InsertServlet")
public class InsertServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        
        String url = "jdbc:mysql://127.0.0.1:3306/WebTest";
        String user = "root";//数据库名
        String passwd = "1473992017";//登录数据库密码

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String information = request.getParameter("information");
        String[] hobbies = request.getParameterValues("hobby");
        String hobby = String.join(",", hobbies); // 使用逗号作为分隔符
        
        try {
            // 加载JDBC驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            //1、注册驱动
            Driver driver = new com.mysql.jdbc.Driver();
            DriverManager.registerDriver(driver);
            //2.获取连接
            Connection connection = DriverManager.getConnection(url, user, passwd);
            //3、获取数据库操作对象
            Statement statement = connection.createStatement();
            //4.sql语句
            String sql = "insert into user_info (username, password, information, hobby) " +
                    "VALUES ('" + username + "', '" + password + "', '" + information + "', '" + hobby + "')";
            //5.执行sql语句后的结果
            int count = statement.executeUpdate(sql);
            
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        
        request.getRequestDispatcher("SelectServlet").forward(request,response);
    }
}
